package session;

import model.Carpool;
import play.libs.Crypto;
import play.libs.Json;
import play.mvc.Controller;
import play.mvc.Http;

import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: Tom
 * Date: 19-2-14
 * Time: 15:02
 */
public class CookieManager {

    private static int THREE_MONTHS = 7889231;
    private static int THIRTY_MINUTES = 1800;

    public static void setRememberMe(String email){
        Controller.response().setCookie("rememberme", Crypto.encryptAES(email), THREE_MONTHS);
    }

    public static String getRememberMe(){
        Http.Cookie rememberme = Controller.request().cookies().get("rememberme");
        if (rememberme != null){
            return Crypto.decryptAES(rememberme.value());
        }
        return null;
    }


    public static void setGroup_ids(List<?> groups){
        if (groups.size() < 1) return;

        ArrayList<String> group_ids;
        if (groups.get(0) instanceof Carpool){
            group_ids = new ArrayList<>();

            for (Object group : groups) {
                Carpool c = (Carpool) group;
                group_ids.add(c.getId());
            }
        }
        else {
            group_ids = (ArrayList<String>) groups;
        }

        String val = SessionManager.getEmail() + "-" + Json.toJson(group_ids).toString();
        Controller.response().setCookie("groups", Crypto.encryptAES(val), THIRTY_MINUTES);
    }


    public static String getGroup_ids(){
        Http.Cookie groups = Controller.request().cookies().get("groups");
        if (groups != null){
            String decrypted = Crypto.decryptAES(groups.value());
            String[] groups_cookie_val = decrypted.split("-");

            if (groups_cookie_val[0].equals(SessionManager.getEmail())){
                return groups_cookie_val[1];
            }
        }
        return null;
    }


}
